//路由守卫，拦截路由
import { ElMessage } from 'element-plus'
import { RouteLocationNormalized, Router } from "vue-router";
// import  useApi from "@/api/user" 后面项目发送请求验证token

import {CacheEnum} from "@/enum/userEnum"

import   utils from "@/utils/index"

class Guard{

    constructor(private router: Router) {}
    public run(){
     
        this.router.beforeEach(this.beforeEach.bind(this))


    }

    //前置路由函数(拦截)
    private  async beforeEach(to:RouteLocationNormalized,from:RouteLocationNormalized){ 
        sessionStorage.setItem("currentPage",to.name as string)//记录现在的页面
        
                if(to.meta.auth&& !this.getToken() && sessionStorage.getItem("userInfo")==null )   {
                    
                    
                    ElMessage({
                         message: '请您登录~~',
                         type: 'warning',
                         grouping: true,
                       })
                    return {name:"auth.login"} 
                }
                if(to.meta.guest && this.getToken() && sessionStorage.getItem("userInfo")!=null)  {
            
                    ElMessage({
                         message: '您已经登录~~',
                         type: 'warning',
                         grouping: true,
                       })
                     return from
                }   
                if(to.name!="auth.login"){
                    // this.setRedirect(to.name)
                    //应该存到session里面,
                    sessionStorage.setItem("redirect_router_name",to.name as string)//记录之前的页面
                   

                }
                
         
         
          }

    //获取token信息
private getToken():string|null{
    
     return utils.store.get(CacheEnum.TOKEN_NAME)
}

private setRedirect(value:any):void{
    
      utils.store.set(CacheEnum.REDIRECT_ROUTER_NAME,value)
}



}
export default  (router: Router)=>{
     new Guard(router).run()
}
